from fastapi import FastAPI, Form
from tortoise import Tortoise, fields
from tortoise.models import Model
from tortoise.contrib.fastapi import HTTPNotFoundError
from tortoise.contrib.pydantic import pydantic_model_creator
from pydantic import BaseModel

app = FastAPI()

# 定义 Pydantic 模型
class Form1(BaseModel):
    orderNumber: str
    batchNumber: str
    materialName: str

# 定义 ORM 模型
class Form_1_Data(Model):
    id = fields.IntField(pk=True)
    orderNumber = fields.CharField(max_length=512)
    batchNumber = fields.CharField(max_length=512)
    materialName = fields.CharField(max_length=512)

    class PydanticMeta:
        # 指定 Pydantic 模型和 ORM 模型之间的映射关系
        model = Form1

# 创建数据库连接
Tortoise.init_models(["__main__"], "models")

# 提交表单数据路由
@app.post("/submit-form-1")
async def submit_form(formData: Form_1_Data = Form(...)):
    # 将 Form_1_Data ORM 模型对象保存到数据库中
    await formData.save()
    return {"message": "Form data submitted successfully"}


# 测试创建表单数据
@app.post("/test-create-form-data")
async def test_create_form_data(formData: Form1):
    # 创建 ORM 模型对象
    orm_instance = Form_1_Data(**formData.dict())
    # 保存 ORM 模型对象到数据库
    await orm_instance.save()
    return {"message": "Form data created successfully"}


# 获取表单数据路由
@app.get("/get-form-data/{form_id}")
async def get_form_data(form_id: int):
    # 通过 ID 查询数据库中的表单数据
    form_data = await Form_1_Data.filter(id=form_id).first()
    # 如果没有找到数据，则返回 404 错误
    if not form_data:
        raise HTTPNotFoundError(detail="Form data not found")
    return await pydantic_model_creator(Form_1_Data)(form_data)


# 启动应用程序
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
